import path from 'path';

import artTemplate from 'art-template';
import SvgCapture from 'svg-captcha';

import type {
  KoaContext,
} from '@/types/koa';

import {
  generateRandomNumber,
} from '@/tools/random';

import {
  RedisDB,
} from '@/db/redis.db';
import sendEmail from '@/service/email.service';

import {
  SEND_EMAIL_ERROR,
} from '@/constant/error/server.error';

// tips 用户邮箱注册验证码
export const emailRegisterVerifyCode = async (ctx: KoaContext) => {
  const { email } = ctx.request.body;

  const code = generateRandomNumber(6);
  try {
    await sendEmail({
      address: email as string,
      title: '邮箱注册验证码',
      content: artTemplate(path.join(__dirname, '../template/register'), { code }),
    });
    RedisDB.set(`EMAIL_REGISTER_VERIFY_CODE_${email}`, code);
    RedisDB.expire(`EMAIL_REGISTER_VERIFY_CODE_${email}`, 60 * 3);
  } catch (error) {
    return ctx.app.emit('error', SEND_EMAIL_ERROR, ctx);
  }

  ctx.body = {
    code: 200,
    message: '验证码已发送, 请注意查收',
  };
};

// tips 图形验证码
export const graphicsVerifyCode = async (ctx: KoaContext) => {
  const { graphicsVerifyCodeKey } = ctx.request.body;

  if (!graphicsVerifyCodeKey?.trim()) {
    return ctx.app.emit('error', {
      code: 400,
      message: '缺失图形验证码key',
    }, ctx);
  }

  // todo 待定是否用 正则 约束字段

  const captcha = SvgCapture.create({
    size: 6,
    width: 100,
    height: 30,
    fontSize: 34,
  });

  const code = captcha.text;

  RedisDB.set(`GRAPHICS_VERIFY_CODE_${graphicsVerifyCodeKey}`, code);

  // 设置 十分钟后过期
  RedisDB.expire(`GRAPHICS_VERIFY_CODE_${graphicsVerifyCodeKey}`, 60 * 10);

  ctx.body = {
    code: 200,
    message: '图形验证码',
    data: captcha.data,
  };
};
